from django.shortcuts import render, redirect
from app_article.models import Article
from app_blog.models import Blog, Advertisement
from lib.CommonPager import Pagination


def pager(request, article_all):
    # 制作分页器
    _current_page = request.GET.get('page', 1)
    _all_count = article_all.count()
    _page_obj = Pagination(current_page=_current_page, all_count=_all_count, per_page_num=10, pager_count=5)
    if not article_all:
        article_data = article_all
    else:
        article_data = article_all[_page_obj.start:_page_obj.end]
    page_html = _page_obj.page_html()
    return article_data, page_html


def home(request):
    # 文章数据
    article_all = Article.objects.exclude(is_delete=True).all()
    # 分页器
    article_data, page_html = pager(request=request, article_all=article_all)
    # 广告数据
    adv_all = Advertisement.objects.all()
    return render(request, 'home.html', locals())


def site(request, username, condition=None, params=None, *args, **kwargs):
    '''
    :param request:
    :param username:站点必须
    :param condition:指定条件 如按分类 按标签 按归档
    :param params:指定参数 如分类id 标签id 日期
    :return:返回article_data
    '''
    blog_obj = Blog.objects.get(userinfo__username=username)
    if not blog_obj:
        return render(request, 'error.html')
    article_data = blog_obj.article_set.order_by('-create_time').exclude(is_delete=True).all()
    # 如果有指定条件，使用筛选条件返回数据
    if condition and params:
        if condition == 'category':
            article_data = blog_obj.article_set.filter(category_id=int(params))
        elif condition == 'tag':
            article_data = blog_obj.article_set.filter(tags=int(params))
            # print(article_data.count())
        elif condition == 'archive':
            year, month = params.split('-')
            article_data = blog_obj.article_set.filter(create_time__year=year, create_time__month=month)
        else:
            return redirect(to='site', username=username)

    # 制作分页器
    article_data, page_html = pager(request=request, article_all=article_data)
    return render(request, 'site.html', locals())



